package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.concurrent.TimeUnit;



//该拦截器用于让有token的用户刷新token时长，让没有token即还未登录的用户加入用户连接池
//可以分成登录和未登录，登录的用户就添加进连接池。如果没登录就看下一个拦截器。


public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token=request.getHeader("authorization");

        //如果token是空，直接就跳过拦截器，让下一个登录拦截器判断是否登录
        if(StrUtil.isBlank(token)){
            return true;
        }
        //通过token获取用户信息
        String key=RedisConstants.LOGIN_USER_KEY+token;

        Map<Object,Object> userMap=stringRedisTemplate.opsForHash().entries(key);
        //如果获取不到，可能是token已经失效，不管，还是让后面来判断
        if(userMap==null){
            return true;
        }

        //那么有用户，也就是在登录状态,添加进连接池，那么下一个拦截器就不会拦截了
        UserDTO userDTO=BeanUtil.fillBeanWithMap(userMap,new UserDTO(),false);

        UserHolder.saveUser(userDTO);

        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
